using Domain;
using ErrorCode;
using Infrastructure;
using MediatR;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using RabbitTraceability.Api.Applications.Command;
using System;
using System.Threading;
using System.Threading.Tasks;

namespace RabbitTraceability.Api.Applications.CommandHandler
{
    /// <summary>
    /// 删除保健信息的命令处理器
    /// </summary>
    public class DeleteHealthCareInfoCommandHandler : IRequestHandler<DeleteHealthCareInfoCommand, bool>
    {
        private readonly IRepository<HealthCareInfo> _healthCareRepository;
        private readonly ILogger<DeleteHealthCareInfoCommandHandler> _logger;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="healthCareRepository">保健信息仓储</param>
        /// <param name="logger">日志记录器</param>
        public DeleteHealthCareInfoCommandHandler(
            IRepository<HealthCareInfo> healthCareRepository,
            ILogger<DeleteHealthCareInfoCommandHandler> logger)
        {
            _healthCareRepository = healthCareRepository;
            _logger = logger;
        }

        /// <summary>
        /// 处理删除保健信息的命令
        /// </summary>
        /// <param name="request">请求命令</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>是否删除成功</returns>
        public async Task<bool> Handle(DeleteHealthCareInfoCommand request, CancellationToken cancellationToken)
        {
            _logger.LogInformation("开始删除保健信息，保健编号：{HealthCareId}", request.HealthCareId);

            try
            {
                // 参数验证
                if (string.IsNullOrWhiteSpace(request.HealthCareId))
                {
                    _logger.LogWarning("保健编号不能为空");
                    throw new ApiException(ResultCode.参数错误, "保健编号不能为空");
                }

                // 查询要删除的保健信息
                var healthCareInfo = await _healthCareRepository.GetAll()
                    .FirstOrDefaultAsync(h => h.HealthCareId == request.HealthCareId && !h.IsDeleted, cancellationToken);

                if (healthCareInfo == null)
                {
                    _logger.LogWarning("未找到保健信息，保健编号：{HealthCareId}", request.HealthCareId);
                    throw new ApiException(ResultCode.数据不存在, $"未找到保健编号为 {request.HealthCareId} 的保健信息");
                }

                // 检查保健信息是否已经被删除
                if (healthCareInfo.IsDeleted)
                {
                    _logger.LogWarning("保健信息已被删除，保健编号：{HealthCareId}", request.HealthCareId);
                    throw new ApiException(ResultCode.操作失败, $"保健编号为 {request.HealthCareId} 的保健信息已被删除");
                }

                // 执行软删除
                await _healthCareRepository.DeleteAsync(healthCareInfo);

                _logger.LogInformation("成功删除保健信息，保健编号：{HealthCareId}，关联批次：{ProductionBatch}", 
                    request.HealthCareId, healthCareInfo.ProductionBatch);

                return true;
            }
            catch (ApiException)
            {
                // 重新抛出API异常
                throw;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "删除保健信息时发生异常，保健编号：{HealthCareId}", request.HealthCareId);
                throw new ApiException(ResultCode.InternalServerError, "删除保健信息失败");
            }
        }
    }
} 